<template>
  <!-- 搜索工作栏 -->
  <div class="header">
    <div class="search-tools">
      <el-row style="margin-bottom: 10px; width: 100%">
        <el-col :span="5">
          <el-input
            v-model="searchParams.title"
            :style="{ width: '220px' }"
            placeholder="请输入标题"
            size="small"
            clearable
          />
        </el-col>
        <el-col :span="5">
            <el-select
                v-model="searchParams.typeId"
                size="small"
                clearable
                :style="{ width: '220px'}"
                placeholder="请选择分类">
                <el-option
                    v-for="ele in columnList"
                    :key="ele.value"
                    :label="ele.label"
                    :value="ele.value">
                </el-option>
            </el-select>
        </el-col>
        <el-col :span="5">
            <el-select
                v-model="searchParams.status"
                size="small"
                clearable
                :style="{ width: '220px'}"
                placeholder="请选择发布动态">
                <el-option
                    v-for="ele in activeList"
                    :key="ele.value"
                    :label="ele.label"
                    :value="ele.value">
                </el-option>
            </el-select>
        </el-col>
        <el-col :span="4">
          <el-button size="small" @click="resetSearch">重置</el-button>
          <el-button
            size="small"
            type="primary"
            @click="handleSearch"
          >搜索</el-button>
          <el-button
            size="small"
            type="primary"
            @click="handleAdd"
          >新建</el-button>
        </el-col>
      </el-row>
      <!-- <SearchBar :searchConfig="searchConfig"
                @transferSearchParams="transferSearchParams"
                @search="handleSearch"
                @resetSearchParams="handleSearch"
                ref="formParams" labelWidth="100px" labelPosition="right" style="margin: 0 0 15px 0">
                <el-button slot="inner" @click="handleAdd" size="small" type="primary">新建</el-button>
            </SearchBar> -->
    </div>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <!-- 按钮批量操作(发布:release,不发布:noRelease,删除:delete,更换栏目:typeIds,还原:recovery,月榜:month,周榜:week) -->
        <el-button
          :disabled="tableSelectList.length === 0"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchOperate('noRelease')"
        >
          批量不发布
        </el-button>
        <el-button
          :disabled="tableSelectList.length === 0"
          type="danger"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchOperate('delete')"
        >
          批量删除
        </el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleSetRanking('month')"
        >
          设置月榜
        </el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleSetRanking('week')"
        >
          设置周榜
        </el-button>
        <el-button
          :disabled="tableSelectList.length === 0"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchOperate('release')"
        >
          批量发布
        </el-button>
        <el-button
          :disabled="tableSelectList.length === 0"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchOperate('month')"
        >
          批量纳入月榜
        </el-button>
        <el-button
          :disabled="tableSelectList.length === 0"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBatchOperate('week')"
        >
          批量纳入周榜
        </el-button>
      </el-col>
    </el-row>
    <Table
      ref="tableList"
      class="search-result-table"
      :table-config="tableConfig"
      :table-data="tableData"
      :total="total"
      :page-no="pageNo"
      :page-size="pageSize"
      :max-height="580"
      @sortChange="sortChange"
      @handleSelectionChange="
        (val) => {
          tableSelectList = val;
        }
      "
      @handleChangePage="handleChangePage"
    >
      <template slot="id" slot-scope="scope">
        <div class="title-box">
          <span>{{ scope.data.index + (pageNo - 1) * pageSize + 1 }}</span>
        </div>
      </template>
      <template slot="title" slot-scope="scope">
        <div class="title-box">
          <div class="ranking-icons">
            <span
              v-if="
                scope.data.row.ranking &&
                  scope.data.row.ranking.indexOf('2') > -1
              "
              class="icon-item"
            >月榜</span>
            <span
              v-if="
                scope.data.row.ranking &&
                  scope.data.row.ranking.indexOf('1') > -1
              "
              class="icon-item"
            >周榜</span>
            <span
              v-if="
                scope.data.row.isTop === 1
              "
              class="icon-item"
            >置顶</span>
          </div>
          <span>{{ scope.data.row.title }}</span>
        </div>
      </template>
      <el-table-column align="center" label="操作" width="460">
        <template slot-scope="scope">
          <div class="btn-box">
            <span
              class="btns width40"
              @click="handleView(scope.row)"
            >查看</span>
            <!-- 是否置顶(0:未置顶1:已置顶) -->
            <span
              v-if="scope.row.isTop === 0"
              class="btns width50"
              @click="handleSetTop(scope.row)"
            >置顶</span>
            <span
              v-if="scope.row.isTop === 1"
              class="btns width50"
              @click="handleSetTop(scope.row)"
            >取消置顶</span>
            <span
              v-if="scope.row.status === '1'"
              class="btns width50"
              @click="handleCancelPush(scope.row, 'noRelease')"
            >不发布</span>
            <span
              v-if="scope.row.status === '0'"
              class="btns width50"
              @click="handleCancelPush(scope.row, 'release')"
            >发布</span>
            <span
              class="btns width40"
              @click="handleEdit(scope.row)"
            >编辑</span>
            <span
              class="btns delete width40"
              @click="handleDelete(scope.row)"
            >删除</span>
            <span
              v-if="scope.row.ranking && scope.row.ranking.indexOf('2') > -1"
              class="btns width80"
              @click="handleCancelRanking(scope.row, 'month')"
            >不纳入月榜</span>
            <span
              v-if="!scope.row.ranking || scope.row.ranking.indexOf('2') === -1"
              class="btns width80"
              @click="handleSetMonthRanking(scope.row, 'month')"
            >纳入月榜</span>
            <span
              v-if="scope.row.ranking && scope.row.ranking.indexOf('1') > -1"
              class="btns width80"
              @click="handleCancelRanking(scope.row, 'week')"
            >不纳入周榜</span>
            <span
              v-if="!scope.row.ranking || scope.row.ranking.indexOf('1') === -1"
              class="btns width80"
              @click="handleSetMonthRanking(scope.row, 'week')"
            >纳入周榜</span>
          </div>
        </template>
      </el-table-column>
    </Table>
    <AddPop ref="addPop" @addSuccess="handleSearch" />
    <ViewNews ref="viewNews" />
    <SetRankingList
      ref="setRankingList"
      @getTableData="getTableData"
      @success="handleSearch"
    />
  </div>
</template>
<script>
import { TYPE, leftSearchConfig, leftTableConfig } from './initData'
// import FormGroup from '@/views/components/FormGroup';
import SearchBar from '@/views/components/SearchBar'
import Table from '@/views/components/Table'
import AddPop from './components/addPop.vue'
import ViewNews from './components/viewNews.vue'
import SetRankingList from './components/setRankingList.vue'
import {
  getTableList,
  updateBatch,
  topping,
  deleteNewsRankingInfo,
  getColumnList
} from '@/api/content-manage/researchResult.js'
import { formatDate } from '@/utils/index.js'

const tipsEnum = {
  noRelease: '不发布',
  delete: '删除',
  release: '发布',
  month: '纳入月榜',
  week: '纳入周榜'
}
export default {
  name: 'NewsList',
  components: {
    SearchBar,
    Table,
    AddPop,
    ViewNews,
    SetRankingList
  },
  data() {
    return {
      searchConfig: JSON.parse(JSON.stringify(leftSearchConfig)),
      tableConfig: leftTableConfig,
      tableData: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      tableSelectList: [],
      searchParams: {},
      sortingFields: null,
      columnList: [],
      activeList: [
        { label: '未发布', value: '0' },
        { label: '已发布', value: '1' }
      ]
    }
  },
  mounted() {
    this.getList()
    this.getColumnList()
  },
  methods: {
    transferSearchParams(params) {
      this.searchParams = params
    },
    async resetSearch() {
      this.searchParams = {}
      this.sortingFields = null
      this.$refs.tableList && this.$refs.tableList.$children[0].clearSort()
      this.handleSearch()
    },
    handleSearch() {
      this.pageNo = 1
      this.getList()
    },
    async getList() {
      const { code, data } = await getTableList({
        ...this.searchParams,
        type: TYPE, // 1:新闻栏目2:成果类型
        sortingFields: this.sortingFields,
        pageNo: this.pageNo,
        pageSize: this.pageSize
      })

      if (code === 0) {
        const list = data.list.map((v) => {
          return {
            ...v,
            releaseTimeStr: formatDate(v.releaseTime),
            updateTimeStr: formatDate(v.updateTime),
            statusStr: v.status === '0' ? '未发布' : '发布'
          }
        })
        this.tableData = list
        this.total = data.total
      } else {
        this.tableData = []
      }
    },

    // 获取栏目列表
    async getColumnList() {
      this.columnList = await this.columnListApi()
      // const configList = JSON.parse(JSON.stringify(leftSearchConfig))
      // configList.forEach(ele => {
      //     if (ele.keyIndex === 'typeId') {
      //         ele.options = this.columnList;
      //     }
      // });
      // this.searchConfig = configList;
    },

    // 获取栏目列表
    async columnListApi() {
      let columnList = []
      const { code, data } = await getColumnList({
        pageNo: 1,
        pageSize: 1000,
        type: TYPE,
        status: '1'
      })
      if (code === 0 && data && data.list && data.list.length > 0) {
        columnList = data.list.map((v) => {
          return {
            label: v.name,
            value: v.id
          }
        })
      }
      return columnList
    },

    // 批量操作group
    async handleBatchOperate(operate) {
      const confirmPopEnum = [
        'noRelease',
        'release',
        'delete',
        'month',
        'week'
      ]
      let ableSelectList = JSON.parse(JSON.stringify(this.tableSelectList))
      if (operate === 'noRelease') {
        ableSelectList = this.tableSelectList.filter((v) => v.status === '1')
      } else if (operate === 'release') {
        ableSelectList = this.tableSelectList.filter((v) => v.status === '0')
      } else if (operate === 'month') {
        // row.ranking.indexOf('2')
        ableSelectList = this.tableSelectList.filter(
          (v) => !v.ranking || v.ranking.indexOf('2') === -1
        )
      } else if (operate === 'week') {
        ableSelectList = this.tableSelectList.filter(
          (v) => !v.ranking || v.ranking.indexOf('1') === -1
        )
      }

      if (confirmPopEnum.indexOf(operate) > -1) {
        const remarkEnum = {
          noRelease: '已发布',
          release: '未发布',
          month: '非月榜',
          week: '非周榜'
        }
        if (ableSelectList.length === 0) {
          const remark = operate === 'noRelease' ? '已发布' : '未发布'
          this.$message.warning(`请选择${remarkEnum[operate]}成果`)
          return
        }
        this.$confirm(`是否确认${tipsEnum[operate]}?`, '提示').then(
          async() => {
            const { code, msg } = await updateBatch({
              ids: ableSelectList.map((v) => v.id),
              operate,
              typeId: '',
              type: TYPE
            })
            if (code !== 0) {
              this.$message.error(msg)
              return
            }
            this.handleSuccessCall()
          }
        )
      }
    },

    handleSetRanking(operate) {
      this.$refs.setRankingList && this.$refs.setRankingList.open({ operate })
    },
    handleSuccessCall() {
      this.$message.success('操作成功')
      this.tableSelectList = []
      this.getList()
    },

    // 切换页码、页数
    handleChangePage({ pageNo, pageSize }) {
      this.pageNo = pageNo
      this.pageSize = pageSize
      this.getList()
    },

    // 查看
    handleView(row) {
      this.$refs.viewNews && this.$refs.viewNews.open(row.id)
    },
    handleSetTop(row) {
      this.$confirm(
        row.isTop === 0 ? '是否确定取消置顶？' : '是否确定置顶',
        '设置置顶'
      ).then(async() => {
        const { code, msg } = await topping({
          id: row.id,
          isTop: row.isTop === 0 ? 1 : 0,
          type: TYPE
        })
        if (code === 0) {
          this.$message.success(row.isTop === 0 ? '置顶成功' : '取消置顶成功')
          this.handleSearch()
        } else {
          this.$message.error(msg)
        }
      })
    },
    // 暂停发布
    async handleCancelPush(row, operate) {
      const mark = operate === 'noRelease' ? '不发布' : '发布'
      this.$confirm(`是否确认${mark}?`, '提示').then(async() => {
        const { code } = await updateBatch({
          ids: [row.id],
          operate,
          typeId: '',
          type: TYPE
        })
        if (code !== 0) return
        this.$message.success('操作成功')
        this.getList()
      })
    },

    async handleSetMonthRanking(row, operate) {
      const remark = operate === 'month' ? '月榜' : '周榜'
      this.$confirm(`是否确认纳入${remark}?`, '提示').then(async() => {
        const { code, msg } = await updateBatch({
          ids: [row.id],
          operate,
          type: TYPE
        })
        if (code !== 0) {
          this.$message.error(msg)
          return
        }
        this.handleSuccessCall()
      })
    },
    // 点击不纳入月榜
    handleCancelRanking(row, operate) {
      const remark = operate === 'month' ? '月榜' : '周榜'
      this.$confirm(`确定不纳入${remark}?`, '提示').then(() => {
        this.delete({ ids: [row.id], operate })
      })
    },
    async delete({ ids, operate }) {
      const { code, msg } = await deleteNewsRankingInfo({
        ids,
        operate,
        type: TYPE,
        queryType: 'news'
      })
      if (code === 0) {
        this.$message.success('操作成功')
        this.handleSuccessCall()
      } else {
        this.$message.error(msg)
      }
    },
    // 编辑
    async handleEdit(row) {
      this.columnList = await this.columnListApi()
      this.$refs.addPop &&
        this.$refs.addPop.open({
          popType: 'edit',
          id: row.id,
          columnList: this.columnList
        })
    },
    // 删除
    async handleDelete(row) {
      this.$confirm(`确定删除?`, '提示').then(async() => {
        const { code, msg } = await updateBatch({
          ids: [row.id],
          operate: 'delete',
          typeId: '',
          type: TYPE
        })
        if (code !== 0) {
          this.$message.erorr(msg)
          return
        }
        this.$message.success('删除成功')
        this.handleSuccessCall()
      })
    },
    // 新建
    async handleAdd() {
      this.columnList = await this.columnListApi()
      this.$refs.addPop &&
        this.$refs.addPop.open({
          popType: 'add',
          columnList: this.columnList
        })
    },
    // 获取排序后的榜单
    getTableData(tableData) {
      // console.log(tableData, '----tableData');
    },

    // 点击排序
    sortChange(sortingFields) {
      this.sortingFields = sortingFields
      this.handleSearch()
    }
  }
}
</script>
<style lang="scss">
.search-result-table {
  .el-table__cell {
    position: relative;
    padding: 20px 0;
  }
}
</style>
<style lang="scss" scoped>
.header {
  display: flex;
  flex-direction: column;
  padding: 0 20px;

  .search-tools {
    display: flex;
    justify-content: space-between;
  }

  .title-box {
    // position: relative;

    .ranking-icons {
      position: absolute;
      left: 0;
      top: 0;

      .icon-item {
        color: blue;
        border: 1px solid blue;
        margin-right: 3px;
        padding: 0 2px;
      }
    }
  }
  .btn-box {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .btns {
      color: #02a7f0;
      cursor: pointer;
      display: inline-block;
    }

    .width50 {
      width: 60px;
    }

    .width40 {
      width: 40px;
    }

    .width80 {
      width: 80px;
    }

    .delete {
      color: #ff4949;
    }
  }
}
</style>
